﻿//------------------------------------------------------------------------------
// ╭─────────────────────────────╮
// │ ╭─╮     ╭─╮              TM │   ╠═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╣
// │ │ │     │ │                 │                                           ☺  
// │ │ ╰───╮ │ │ ╭─────╮ ╭─────╮ │     Name:Wedn.Net XML序列化操作助手类  ♮ ♪ ♩
// │ │ ╭─╮ │ │ │ │ ╭─╮ │ │ ╭─╮ │ │                                     ♫ ♭      
// │ │ ╰─╯ │ │ │ │ ╰─╯ │ │ ╰─╯ │ │     Author:iceStone                ♬ ♪       
// │ └─────╯ └─╯ ╰─────╯ ╰───╮ │ │     Chinese:汪磊                              
// │                     ┌───╯ │ │                                              
// │                     ╰─────╯ │   ╠═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╣
// ╰─────────────────────────────╯                                              
//------------------------------------------------------------------------------
using System;
using System.IO;
using System.Text;
using System.Web;
using System.Xml;
using System.Xml.Serialization;

namespace Wedn.Net.Utility
{
    /// <summary>
    /// XML序列化操作助手类
    /// </summary>
    public static class XmlHelper
    {
        #region XML序列化 static string XmlSerialize(object obj, Encoding encoding)
        /// <summary>
        /// XML序列化
        /// </summary>
        /// <param name="stream">流</param>
        /// <param name="obj">对象</param>
        /// <param name="encoding">编码</param>
        private static void XmlSerializeInternal(Stream stream, object obj, Encoding encoding)
        {
            if (obj == null)
                throw new ArgumentNullException("o");
            if (encoding == null)
                throw new ArgumentNullException("encoding");
            XmlSerializer serializer = new XmlSerializer(obj.GetType());
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.NewLineChars = "\r\n";
            settings.Encoding = encoding;
            settings.IndentChars = "    ";
            using (XmlWriter writer = XmlWriter.Create(stream, settings))
            {
                serializer.Serialize(writer, obj);
                writer.Close();
            }
        }
        #endregion

        #region 将一个对象序列化为XML字符串(UTF-8编码) +static string XmlSerialize(object obj)
        /// <summary>
        /// 将一个对象序列化为XML字符串(UTF-8编码)
        /// </summary>
        /// <param name="obj">要序列化的对象</param>
        /// <returns>序列化产生的XML字符串(UTF-8编码)</returns>
        public static string XmlSerialize(object obj)
        {
            return XmlSerialize(obj, Encoding.UTF8);
        } 
        #endregion

        #region 将一个对象序列化为XML字符串 +static string XmlSerialize(object obj, Encoding encoding)
        /// <summary>
        /// 将一个对象序列化为XML字符串
        /// </summary>
        /// <param name="obj">要序列化的对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>序列化产生的XML字符串</returns>
        public static string XmlSerialize(object obj, Encoding encoding)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                XmlSerializeInternal(stream, obj, encoding);

                stream.Position = 0;
                using (StreamReader reader = new StreamReader(stream, encoding))
                {
                    return reader.ReadToEnd();
                }
            }
        }
        #endregion

        #region 将一个对象按XML序列化的方式写入到一个文件(虚拟路径)UTF-8 +static void XmlSerializeToFile(object obj, string virtualPath)
        /// <summary>
        /// 将一个对象按XML序列化的方式写入到一个文件(虚拟路径)UTF-8
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="virtualPath"></param>
        public static void XmlSerializeToFile(object obj, string virtualPath)
        {
            XmlSerializeToFile(obj, HttpContext.Current.Server.MapPath(virtualPath), Encoding.UTF8);
        }
        #endregion

        #region 将一个对象按XML序列化的方式写入到一个文件 +static void XmlSerializeToFile(object obj, string path, Encoding encoding)
        /// <summary>
        /// 将一个对象按XML序列化的方式写入到一个文件
        /// </summary>
        /// <param name="obj">要序列化的对象</param>
        /// <param name="path">保存文件路径</param>
        /// <param name="encoding">编码方式</param>
        public static void XmlSerializeToFile(object obj, string path, Encoding encoding)
        {
            if (string.IsNullOrEmpty(path))
                throw new ArgumentNullException("path");

            using (FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                XmlSerializeInternal(file, obj, encoding);
            }
        }
        #endregion

        #region 从XML字符串(UTF-8编码)中反序列化对象 +static T XmlDeserialize<T>(string str)
        /// <summary>
        /// 从XML字符串(UTF-8编码)中反序列化对象
        /// </summary>
        /// <typeparam name="T">结果对象类型</typeparam>
        /// <param name="str">包含对象的XML字符串</param>
        /// <returns>反序列化得到的对象</returns>
        public static T XmlDeserialize<T>(string str)
        {
            return XmlDeserialize<T>(str, Encoding.UTF8);
        } 
        #endregion

        #region 从XML字符串中反序列化对象 +static T XmlDeserialize<T>(string str, Encoding encoding)
        /// <summary>
        /// 从XML字符串中反序列化对象
        /// </summary>
        /// <typeparam name="T">结果对象类型</typeparam>
        /// <param name="str">包含对象的XML字符串</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>反序列化得到的对象</returns>
        public static T XmlDeserialize<T>(string str, Encoding encoding)
        {
            if (string.IsNullOrEmpty(str))
                throw new ArgumentNullException("s");
            if (encoding == null)
                throw new ArgumentNullException("encoding");

            XmlSerializer mySerializer = new XmlSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream(encoding.GetBytes(str)))
            {
                using (StreamReader sr = new StreamReader(ms, encoding))
                {
                    return (T)mySerializer.Deserialize(sr);
                }
            }
        }
        #endregion

        #region 读入一个虚拟路径文件(UTF-8编码)，并按XML的方式反序列化对象。 +static T XmlDeserializeFromFile<T>(string virtualPath)
        /// <summary>
        /// 读入一个虚拟路径文件(UTF-8编码)，并按XML的方式反序列化对象。
        /// </summary>
        /// <typeparam name="T">结果对象类型</typeparam>
        /// <param name="virtualPath">虚拟路径</param>
        /// <returns>反序列化得到的对象</returns>
        public static T XmlDeserializeFromFile<T>(string virtualPath)
        {
            return XmlDeserializeFromFile<T>(HttpContext.Current.Server.MapPath(virtualPath), Encoding.UTF8);
        }
        #endregion

        #region 读入一个文件，并按XML的方式反序列化对象。 +static T XmlDeserializeFromFile<T>(string path, Encoding encoding)
        /// <summary>
        /// 读入一个文件，并按XML的方式反序列化对象。
        /// </summary>
        /// <typeparam name="T">结果对象类型</typeparam>
        /// <param name="path">文件路径</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>反序列化得到的对象</returns>
        public static T XmlDeserializeFromFile<T>(string path, Encoding encoding)
        {
            if (string.IsNullOrEmpty(path))
                throw new ArgumentNullException("path");
            if (encoding == null)
                throw new ArgumentNullException("encoding");
            if (!File.Exists(path))
                return default(T);
            string xml = File.ReadAllText(path, encoding);
            return XmlDeserialize<T>(xml, encoding);
        }
        #endregion
    }
}
